package com.wennimei.service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wennimei.dao.SoftDAO;
import com.wennimei.domain.Soft;
import com.wennimei.enums.MessageTypeEnum;
import com.wennimei.util.HttpUtil;
import com.wennimei.util.Switcher;

public class SoftService {

    private Logger log = Logger.getLogger(SoftService.class);

    private final long maxExpire = 1000 * 60 * 60;
    
    @Autowired
    private SoftDAO softDAO;

    @Autowired
    private SolrService solrService;

    @Autowired
    private Switcher switcher;

    void init() {

        if (!switcher.isOpen())
            return;

        Integer maxId = softDAO.getMaxId();
        maxId = null == maxId ? 0 : maxId;
        long start = System.currentTimeMillis();
        while (true) {
            
            long expire = System.currentTimeMillis() - start;
            if (expire >= maxExpire)
                return;
            try {
                log.info("start crawl soft " + maxId);
                String url = "http://soft.3g.cn/xuan/xuanInfo.php?id=%s";
                String html = HttpUtil.get(String.format(url, maxId));
                html = html.replaceAll("(\\r|\\t|\\n)", "");
                Pattern p = Pattern
                        .compile(".*<strong><img src=\"(.*)\" width=\".*<div style=\"width:120px; overflow:hidden;\">(.*)<div style=\"display:none.*<div class=\"info-con\"><div>(.*)</span></div>\\s*<div id=\"softmoreinfo.*");
                Matcher m = p.matcher(html);
                String pic = null;
                String title = null;
                String info = null;
                while (m.matches()) {
                    pic = m.group(1);
                    title = m.group(2);
                    info = m.group(3).replaceAll(
                            "<span id=\"more\" style=\"display:none\">", "");
                    break;
                }
                if (null == title)
                    continue;

                softDAO.insert(maxId, title, pic, info);
                solrService.doSoftIndex(maxId, title, pic, info);
                log.info("crawl soft " + maxId + " success!" + title + "  "
                        + pic + " " + info);
            } catch (Exception e) {
                log.error("crawl soft error", e);
            } finally {
                maxId++;
                if (System.currentTimeMillis() - start > 30 * 60 * 1000)
                    return;
            }

        }
    }

    public List<Soft> get(String content) {
        content = content.replaceAll(
                MessageTypeEnum.SOFT_DOWN.getReplaceRegx(), "");
        return this.solrService.searchSoft(content);
    }
}
